/**
 * Title: s.java
 * @author WuJin
 * @date 2020年6月16日
 * @version 1.0
 */
package com.pm.common.aspect;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.pm.common.annotation.MyLog;
import com.pm.entity.po.security.OperatingLog;
import com.pm.entity.po.security.User;
import com.pm.service.security.OperatingLogService;
import com.pm.utils.HttpContextUtils;
import com.pm.utils.IPUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统日志：切面处理类
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {

	@Autowired
	private OperatingLogService operatingLogService;

	// 定义切点 @Pointcut
	// 在注解的位置切入代码
	@Pointcut("@annotation(com.pm.common.annotation.MyLog)")
	public void logPoinCut() {
	}

	// 切面 配置通知
	@AfterReturning("logPoinCut()")
	public void saveSysLog(JoinPoint joinPoint) {
		// 保存日志
		OperatingLog sysLog = new OperatingLog();

		// 从切面织入点处通过反射机制获取织入点处的方法
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		// 获取切入点所在的方法
		Method method = signature.getMethod();
		/*
		 * //返回结果获取
		 * Response response=new Response<>();
		 * System.out.println(signature.getReturnType().cast(response));
		 * System.out.println(response.getCode());
		 */
		// 获取操作
		MyLog myLog = method.getAnnotation(MyLog.class);
		if (myLog != null) {
			String value = myLog.value();
			sysLog.setOperation(value);// 保存获取的操作
		}

		// 获取请求的类名
		String className = joinPoint.getTarget().getClass().getName();
		// 获取请求的方法名
		String methodName = method.getName();
		sysLog.setMethod(className + "." + methodName);

		// 请求的参数
		Object[] args = joinPoint.getArgs();
		// 将参数所在的数组转换成json
		String params = JSON.toJSONString(args);

		sysLog.setParams(params);
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		// 获取用户名
		User user = null;
		try {
			user = (User) request.getAttribute("CurrentUser");
		} catch (Exception e) {
			user = new User(String.valueOf(args[0]), String.valueOf(args[1]));
		}
		if(user==null) {
			user = new User(String.valueOf(args[0]), String.valueOf(args[1]));
		}
		sysLog.setUsername(user.getUsername());
		// 获取用户ip地址
		sysLog.setIp(IPUtils.getIpAddr(request));

		// 调用service保存SysLog实体类到数据库
		log.info(sysLog.getOperation()+":"+sysLog.getParams());
		operatingLogService.add(sysLog);
	}

}
